package com.shujia.scala

import java.io.{BufferedReader, BufferedWriter, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo6IO {
  def main(args: Array[String]): Unit = {
    //java 文件读写
    //scala默认异常已经抛出
    val fileReader = new FileReader("data/students.txt")
    val bufferedReader = new BufferedReader(fileReader)
    //读取第一行
    var line: String = bufferedReader.readLine()
    while (line != null) {
      //println(line)
      //读取下一行
      line = bufferedReader.readLine()
    }
    bufferedReader.close()
    fileReader.close()

    //scala读取文件
    //构建输入流对象
    val source: BufferedSource = Source.fromFile("data/students.txt")
    //读取所有行
    val students: List[String] = source.getLines().toList

    for (student <- students) {
      println(student)
    }

    //省略
    for (elem <- Source fromFile "data/students.txt" getLines) {
      println(elem)
    }

    println("*" * 100)

    //scala中循环
    //面向函数编程：将函数传来传去（1、以函数作为参数，2、以函数作为返回值）
    students.foreach(println)

    source.close()

    //文件写入，使用java的方式
    val fileWriter = new FileWriter("data/scala.txt")
    val bufferedWriter = new BufferedWriter(fileWriter)
    bufferedWriter.write("java")
    bufferedWriter.write("scala")
    bufferedWriter.write("spark")
    bufferedWriter.flush()

    bufferedWriter.close()
    fileWriter.close()
  }
}
